package com.kalvan.admin.gateway.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.kalvan.client.context.RequestContextHolder;
import com.kalvan.client.exception.BizException;
import com.kalvan.commons.constant.AdminContextCacheKey;
import com.kalvan.commons.constant.AdminReturnCode;
import com.kalvan.commons.constant.AuditState;
import com.kalvan.commons.constant.State;
import com.kalvan.commons.db.DataSourceConstants;
import com.kalvan.commons.db.gateway.mapper.GatewayServiceMapper;
import com.kalvan.commons.db.gateway.model.GatewayService;
import com.kalvan.db.mybatis.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.kalvan.commons.constant.AdminContextCacheKey.SERVICES;

/**
 * 服务发布Service实现类
 *
 * @author kalvan
 */
@Slf4j
@Service("gatewayServiceService")
public class GatewayServiceService extends BaseService<GatewayService> {
    @Resource
    GatewayServiceMapper mapper;

    @Override
    public void processParams(Map<String, Object> params) {
        // TODO 查询和下载的条件检查
        convertBetweenParams(params, "maxAccess", false, false);
        convertBetweenParams(params, "times", false, false);
    }

    @Override
    @Transactional(value = DataSourceConstants.GATEWAY_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int add(GatewayService gatewayService) {
        // TODO 填充数据,选择字段进行检查，更新人，更新时间，查重
        GatewayService gatewayServiceQuery = new GatewayService();

        if (mapper.selectCount(gatewayServiceQuery) > 0) {
            throw new BizException(AdminReturnCode.DATA_REPEAT);
        }
        gatewayService.setAuditApplicant(String.valueOf(RequestContextHolder.getContext().get(AdminContextCacheKey.USER_NAME)));
        // TODO 新增审核,业务状态不生效,审核状态为待审核
        gatewayService.setState(State.DISABLE.getCode());
        gatewayService.setAuditState(AuditState.ADD.getCode());
        return mapper.insertSelective(gatewayService);
    }

    @Override
    @Transactional(value = DataSourceConstants.GATEWAY_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int edit(GatewayService gatewayService) {
        GatewayService gatewayServiceDb = mapper.selectByUk(gatewayService.getId());
        if (gatewayServiceDb == null) {
            throw new BizException(AdminReturnCode.DATA_NOT_EXISTS);
        }
        // TODO 更新指定字段，更新人
        GatewayService gatewayServiceNew = new GatewayService();
        gatewayServiceNew.setId(gatewayService.getId());
        gatewayServiceNew.setAuditApplicant(String.valueOf(RequestContextHolder.getContext().get(AdminContextCacheKey.USER_NAME)));

        // TODO 更新审核,将修改内容保存到json临时字段
        if (gatewayServiceDb.getAuditState() != AuditState.PASS.getCode()) {
            throw new BizException(AdminReturnCode.DATA_PROCESSING);
        }
        GatewayService gatewayServiceTemp = new GatewayService();
        gatewayServiceTemp.setService(gatewayService.getService());
        gatewayServiceTemp.setGroupName(gatewayService.getGroupName());
        gatewayServiceTemp.setResource(gatewayService.getResource());
        gatewayServiceTemp.setRouteId(gatewayService.getRouteId());
        gatewayServiceTemp.setState(gatewayService.getState());
        gatewayServiceTemp.setMaxAccess(gatewayService.getMaxAccess());
        gatewayServiceTemp.setTimes(gatewayService.getTimes());
        gatewayServiceTemp.setRemark(gatewayService.getRemark());

        gatewayServiceNew.setAuditState(AuditState.UPDATE.getCode());
        gatewayServiceNew.setAuditTemp(JSONObject.toJSONString(gatewayServiceTemp));
        return mapper.updateByUkSelective(gatewayServiceNew);
    }

    @Override
    @Transactional(value = DataSourceConstants.GATEWAY_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int deleteBatch(Object[] ids) {
        int resultNum = 0;
        for (Object id : ids) {
            // TODO 删除审核
            GatewayService gatewayServiceDb = mapper.selectByUk(id);
            if (gatewayServiceDb.getAuditState() != AuditState.PASS.getCode()) {
                throw new BizException(AdminReturnCode.DATA_PROCESSING);
            }
            GatewayService gatewayServiceNew = new GatewayService();
            gatewayServiceNew.setId(gatewayServiceDb.getId());
            gatewayServiceNew.setAuditApplicant(String.valueOf(RequestContextHolder.getContext().get(AdminContextCacheKey.USER_NAME)));
            gatewayServiceNew.setAuditState(AuditState.DELETE.getCode());
            resultNum = resultNum + mapper.updateByUkSelective(gatewayServiceNew);
        }
        return resultNum;
    }

    @Override
    @Transactional(value = DataSourceConstants.GATEWAY_TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int auditingBatch(Object[] ids, boolean pass) {
        List services = new ArrayList();
        RequestContextHolder.getContext().put(SERVICES, services);
        int resultNum = 0;
        String userCode = String.valueOf(RequestContextHolder.getContext().get(AdminContextCacheKey.USER_NAME));
        for (Object id : ids) {
            GatewayService gatewayServiceDb = mapper.selectByUk(id);
            if (gatewayServiceDb.getAuditApplicant().equals(userCode)) {
                throw new BizException(AdminReturnCode.DATA_SELF_AUDIT);
            }
            if (gatewayServiceDb.getAuditState() == AuditState.PASS.getCode()) {
                continue;
            }
            services.add(gatewayServiceDb.getService());
            GatewayService gatewayServiceNew = new GatewayService();
            if (pass) {
                //修改审核
                if (AuditState.UPDATE.getCode() == gatewayServiceDb.getAuditState()) {
                    String object = gatewayServiceDb.getAuditTemp();
                    if (StringUtils.isBlank(object)) {
                        throw new BizException(AdminReturnCode.DATA_NOT_EXISTS);
                    }
                    GatewayService gatewayService = JSONObject.parseObject(object, GatewayService.class);
                    BeanUtils.copyProperties(gatewayService, gatewayServiceNew);
                }
                //新增审核通过生效
                if (AuditState.ADD.getCode() == gatewayServiceDb.getAuditState()) {
                    gatewayServiceNew.setState(State.ENABLE.getCode());
                }
                //删除审核
                if (AuditState.DELETE.getCode() == gatewayServiceDb.getAuditState()) {
                    resultNum = resultNum + mapper.deleteByUk(gatewayServiceDb);
                    continue;
                }
            } else {
                //新增审核不通过删除
                if (AuditState.ADD.getCode() == gatewayServiceDb.getAuditState()) {
                    resultNum = resultNum + mapper.deleteByUk(gatewayServiceDb);
                    continue;
                }
            }
            gatewayServiceNew.setId(gatewayServiceDb.getId());
            gatewayServiceNew.setAuditUser(userCode);
            gatewayServiceNew.setUpdateTime(DateUtil.date());
            //清除审核标记
            gatewayServiceNew.setAuditState(AuditState.PASS.getCode());
            gatewayServiceNew.setAuditTemp("{}");
            resultNum = resultNum + mapper.updateByUkSelective(gatewayServiceNew);
        }
        return resultNum;
    }

}
